/*
 * Copyright 2008-2009 Daniel Cachapa <cachapa@gmail.com>
 * 
 * This program is distributed under the terms of the GNU General Public Licence Version 3
 * The licence can be read in its entirety in the LICENSE.txt file accompaning this source code,
 * or at: http://www.gnu.org/copyleft/gpl.html
 * 
 * This file is part of WeightWatch.
 *
 * WeightWatch is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, version 3 of the License.
 *
 * WeightWatch is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with the WeightWatch source code. If not, see
 * <http://www.gnu.org/licenses/>.
 */

package net.cachapa.weightwatch;

import net.cachapa.weightwatch.util.Serialize;
import net.cachapa.weightwatch.util.MyDate;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;

public class Value implements Serialize {
	public MyDate date;
	public double weight;
	public double trend;
	public int dbIndex;
	
	public Value() {
		date = new MyDate();
	}

	public Value(MyDate date, double weight) {
		this.date = date;
		this.weight = weight;
	}
	
	public byte[] toByteArray() {
		try {
			ByteArrayOutputStream bout = new ByteArrayOutputStream();
			DataOutputStream dout = new DataOutputStream(bout);

			dout.writeLong(date.getTime());
			dout.writeDouble(weight);
			dout.writeDouble(trend);
			dout.flush();

			return bout.toByteArray();
		} catch (IOException ex) {
			ex.printStackTrace();
			return null;
		}
	}

	public void fromByteArray(byte[] data) {
		try {
			ByteArrayInputStream bin = new ByteArrayInputStream(data);
			DataInputStream din = new DataInputStream(bin);

			date = new MyDate(din.readLong());
			weight = din.readDouble();
			trend = din.readDouble();
		} catch (IOException ex) {
			ex.printStackTrace();
		}
	}

	public String toString() {
		return this.date.toShortString() + ": " + this.weight + " Kg";
	}

	public long compareTo(Object other) {
		long thisTime = this.date.getTime();
		long otherTime = ((Value)other).date.getTime();
		return thisTime - otherTime;
	}
}
